const zh_CN = require('./langs/zh_CN')
const en_US = require('./langs/en_US')

const LOCALE_KEY = 'locale'
const EVENT_LOCALE_CHANGED = 'localeChanged'

const i18n = {
  locale: wx.getStorageSync(LOCALE_KEY) || 'zh_CN',
  messages: {
    zh_CN,
    en_US
  },

  // 获取当前语言
  getLocale() {
    return this.locale
  },

  // 设置语言
  setLocale(locale) {
    this.locale = locale
    wx.setStorageSync(LOCALE_KEY, locale)
    // 触发语言变更事件
    const app = getApp()
    if (app && app.globalData && app.globalData.eventBus) {
      app.globalData.eventBus.emit(EVENT_LOCALE_CHANGED)
    }
  },

  // 获取翻译文本
  t(key) {
    const keys = key.split('.')
    let message = this.messages[this.locale]
    
    for (const k of keys) {
      message = message[k]
      if (!message) return key
    }
    
    return message
  }
}

module.exports = i18n 